package cn.zxh.improvement.gencode.processor.pojo.vo;

import cn.zxh.improvement.gencode.processor.BaseCodeGenProcessor;
import cn.zxh.improvement.gencode.spi.CodeGenProcessor;
import cn.zxh.improvement.gencode.util.GenCodeUtil;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import java.lang.annotation.Annotation;
import java.util.Objects;
import java.util.Set;

/**
 * vo 生成器
 *
 * @author zxh
 * @since 2023/5/6 16:54:03
 */
@AutoService(value = CodeGenProcessor.class)
public class GenVoProcessor extends BaseCodeGenProcessor {

    public static final String SUFFIX = "Vo";

    @Override
    protected void generateClass(TypeElement typeElement, RoundEnvironment roundEnvironment) {
        String className = typeElement.getSimpleName() + SUFFIX;
        TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(className)
                .addModifiers(Modifier.PUBLIC);
        Set<VariableElement> fields = GenCodeUtil.findFields(typeElement, variableElement -> Objects.isNull(variableElement.getAnnotation(IgnoreVo.class)));
        for (VariableElement field : fields) {
            String attribute = field.getSimpleName().toString();
            TypeName typeName = TypeName.get(field.asType());
            String fileDesc = GenCodeUtil.getFileDesc(field);
            FieldSpec fieldSpec = GenCodeUtil.genPrivateField(attribute, fileDesc, typeName);
            MethodSpec genSetMethod = GenCodeUtil.genSetMethod(attribute, fileDesc, typeName);
            MethodSpec genGetMethod = GenCodeUtil.genGetMethod(attribute, fileDesc, typeName);
            typeSpecBuilder.addField(fieldSpec);
            typeSpecBuilder.addMethod(genSetMethod);
            typeSpecBuilder.addMethod(genGetMethod);
        }

        GenCodeUtil.genJavaSourceFile(generatePackage(typeElement), typeElement.getAnnotation(GenVo.class).sourcePath(), typeSpecBuilder.build());
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return GenVo.class;
    }

    @Override
    public String generatePackage(TypeElement typeElement) {
        return typeElement.getAnnotation(GenVo.class).pkgName();
    }
}
